<template>
  <div>
    <a-form :form='form' :labelAlign="'left'" style='max-width: 500px; margin: 40px auto 0;'>
      <!--题目名称-->
      <a-form-item
        label='题目名称'
        :labelCol='labelCol'
        :wrapperCol='wrapperCol'>
        <a-input placeholder='请输入题目名称'
                 ref='firstInput'
                 v-decorator="['title', { initialValue: tempForm.title,  rules: [{required: true, message: '题目名称不能为空'}] }]" />
      </a-form-item>
      
      <!--出题人基本信息展示(从vuex中取)-->
      <a-form-item
        label='出题人信息'
        :labelCol='labelCol'
        :wrapperCol='wrapperCol'>
        <a-descriptions bordered>
          <a-descriptions-item label='姓名' :span='3'>
            {{ $store.state.user.name }}
          </a-descriptions-item>
          
          <a-descriptions-item label='学号'>
            {{ $store.state.user.info.studentId }}
          </a-descriptions-item>
        </a-descriptions>
      </a-form-item>
      
      <!--难度标签设置-->
      <a-form-item
        label='难度标签'
        :labelCol='labelCol'
        :wrapperCol='wrapperCol'>
        <a-select
          placeholder='请选择题目的难度标签'
          v-decorator="['level', { initialValue: tempForm.level, rules: [{required: true, message: '难度标签为必填'}]}]">
          <a-select-option value='0'>简单</a-select-option>
          <a-select-option value='1'>中等</a-select-option>
          <a-select-option value='2'>困难</a-select-option>
        </a-select>
      </a-form-item>
      
      
      <!--标签设置-->
      <a-form-item label='题目标签'
                   :required='true'
                   :labelCol='labelCol'
                   :wrapperCol='wrapperCol'>
        <template v-for='(tag, index) in tempForm.tags'>
          
          <a-tooltip v-if='tag.length > 20' :key='tag' :title='tag'>
            <a-tag class='tags-list' :key='tag' :closable='index !== 0' @close='() => handleClose(tag)'>
              {{ `${tag.slice(0, 20)}...` }}
            </a-tag>
          </a-tooltip>
          
          <a-tag class='tags-list' v-else :key='tag' :closable='index !== 0' @close='() => handleClose(tag)'>
            {{ tag }}
          </a-tag>
        
        </template>
        <a-input
          v-if='inputVisible'
          ref='input'
          type='text'
          :style="{ width: '78px' }"
          v-model='inputValue'
          @change='handleInputChange'
          @blur='handleInputConfirm'
          @keyup.enter='handleInputConfirm'
        />
        <a-tag v-else class='new-tags-button' @click='showInput'>
          <a-icon type='plus' />
          新增标签
        </a-tag>
      </a-form-item>
      
      <a-form-item
        label='分值'
        :labelCol='labelCol'
        :wrapperCol='wrapperCol'
      >
        <a-input placeholder='填写分值(默认10分)'
                 v-decorator="['score', { initialValue: 10, rules: [{required: true, message: '分值必须填写'}] }]">
        </a-input>
      </a-form-item>
    
    </a-form>
    
    
    <a-divider>
      <a-popover>
        <template slot='content'>
          <a-icon type='warning' theme='twoTone' two-tone-color='#eb2f96' />
          必填项
        </template>
        <h2 style='text-align: center;cursor: pointer'>设置题目详细信息
          <a-icon type='save' />
        </h2>
      </a-popover>
    </a-divider>
    <!--markdown编辑器 => topicDetailed-->
    <MavonEditor @getMarkDownContext='getMarkDownContext'
                 :markdown-content='tempForm.detail' />
    
    
    <a-divider>
      <a-popover style='margin-top: 20px;'>
        <template slot='content'>
          <a-icon type='warning' theme='twoTone' two-tone-color='#eb2f96' />
          必填项
        </template>
        <h2 style='text-align: center;cursor: pointer'>设置答题模板
          <a-icon type='form' />
        </h2>
      </a-popover>
    </a-divider>

    <!--<a-form-item
      :required='true'
      label='语言设置'
      :labelCol='{ lg: { span: 8 }, sm: { span: 5 } }'
      :wrapperCol='{ lg: { span: 10 }, sm: { span: 19 } }'
    >
      <a-select
        placeholder='请选择语言'
        default-value='python'
        style='width: 100%;'
        v-decorator="['lang', { initialValue: 'python', rules: [{required: true, message: '分值必须填写'}] }]">
        <a-select-option value='python'>
          Python
        </a-select-option>
        <a-select-option value='java'>
          Java
        </a-select-option>
        <a-select-option value='c'>
          C
        </a-select-option>
        <a-select-option value='c++'>
          C++
        </a-select-option>
      </a-select>
    </a-form-item>-->
    
    <!--代码模板 python/java/c/c++/js => codeTemplate -->
    <BaseIDE @getCodeAnswer='getCodeAnswer' :code-template='tempForm.codeTemplate' />
    
    <!--<a-button icon='plus' style='float: right;margin-bottom: 30px;'>
      添加代码模板
    </a-button>-->
    <!--下一步的按钮-->
    <a-divider />
    <a-form-item :wrapperCol='{span: 19, offset: 11}'>
      <a-button type='primary' @click='nextStep' :loading='loading'>下一步</a-button>
    </a-form-item>
    
    <!--注意事项-->
    <LookOut />
  </div>
</template>

<script>
import MavonEditor from '@/components/Editor/MavonEditor.vue'
import BaseIDE from '@/views/reply/components/BaseIDE.vue'
import LookOut from '@/views/topic/components/LookOut.vue'
import { getTopicDetail, getTopicDetailAndMyAns } from '@/api/newcomerTopic'

export default {
  components: {
    MavonEditor,
    BaseIDE,
    LookOut
  },
  name: 'Step1',
  props: {
    formData: {
      type: Object,
      required: true
    },
    mode: {
      type: String,
      required: false,
      default: 'insert'
    }
  },
  created() {
  },
  data() {
    return {
      // 创建表单
      labelCol: { lg: { span: 5 }, sm: { span: 5 } },
      wrapperCol: { lg: { span: 19 }, sm: { span: 19 } },
      form: this.$form.createForm(this),
      
      // 开启加载动画
      loading: false,
      // 避免直接修改父组件的值
      tempTags: [],
      tempForm: this.formData,
      
      // 标签输入框是否展示
      inputVisible: false,
      // 标签输入框的值
      inputValue: ''
    }
  },
  
  mounted() {
    // 在页面加载完成后，将焦点设置到输入框
    this.getFirstInputFocus()
  },
  methods: {
    nextStep() {
      this.loading = true
      const { form: { validateFields } } = this
      // 先校验，通过表单校验后，才进入下一步
      validateFields((err, values) => {
        this.getFirstInputFocus()
        // 1. 判断代码模板和markdown编辑器是否有内容
        if (this.tempForm.tags.length === 0) {
          this.openNotificationWithIcon('警告', '题目标签个数至少为一个')
          return
        }
        
        // 2. 判断表单是否填完整
        if (!err) {
          // values 为所填的内容 => 添加 tags codeTemplate topicDetailed属性
          values.tags = this.tempForm.tags
          values.detail = this.tempForm.detail
          values.codeTemplate = this.tempForm.codeTemplate
          values.topicId = this.tempForm.topicId
          // 将数据传递给父组件
          if (this.mode === 'insert') {
            this.$emit('nextStep', values)
          } else {
            this.$emit('updateTopic', values)
          }
        }
      })
      this.loading = false
    },
    // 得到子组件传递过来的题目详细信息
    getMarkDownContext(detail) {
      this.tempForm.detail = detail
    },
    getCodeAnswer(codeTemplate) {
      this.tempForm.codeTemplate = codeTemplate
    },
    
    // 删除标签
    handleClose(removedTag) {
      this.tempForm.tags = this.tempForm.tags.filter(tag => tag !== removedTag)
    },
    // 展示添加标签输入框
    showInput() {
      this.inputVisible = true
      // 获取焦点
      this.$nextTick(function() {
        this.$refs.input.focus()
      })
    },
    // 获取标签内容
    handleInputChange(e) {
      this.inputValue = e.target.value
    },
    // 焦点消失或按下回车后进行添加
    handleInputConfirm() {
      
      const inputValue = this.inputValue
      if (inputValue.length >= 10) {
        this.inputVisible = false
        this.openNotificationWithIcon('警告', '单个标签的长度不能超过10')
        return
      }
      if (this.tempForm.tags.length >= 5) {
        this.inputVisible = false
        this.openNotificationWithIcon('警告', '题目标签不能超过5个')
        return
      }
      // 判断输入的元素是否已经存在
      if (inputValue && this.tempForm.tags.indexOf(inputValue) === -1) {
        this.tempForm.tags = [...this.tempForm.tags, inputValue]
      }
      Object.assign(this, {
        inputVisible: false,
        inputValue: ''
      })
    },
    // 获取第一个输入框的焦点
    getFirstInputFocus() {
      this.$nextTick(() => {
        this.$refs.firstInput.focus()
      })
    },
    
    openNotificationWithIcon(message, description) {
      this.$notification['warning']({
        message,
        description
      })
    }
  }
}
</script>

<style lang='less' scoped>

.tags-list {
  background-color: #f2f3f4;
  cursor: pointer;
  color: #85858a;
  border: none;
  padding: 5px;
  border-radius: 10px;
}

.new-tags-button {
  background-color: #f2f3f4;
  cursor: pointer;
  color: #7d7def;
  border: none;
  padding: 5px;
  border-radius: 10px;
}

/deep/ .CodeMirror {
  height: 200px;
  width: 100%;
}

</style>
